<?php
/**
 * Created by PhpStorm.
 *
 * @Date: 2017-08-04
 * @Time: 15:44
 * @Author: cdkay
 * @Email: network@iyuanma.net
 *
 * @File： Live.php
 */
namespace app\api\controller;

use app\api\model\live\Live as LiveModel;
use app\admin\model\live\LiveChannel;
use app\api\model\LiveToken;
use app\common\controller\Base;
use app\common\model\ApiResponse;
use app\common\model\LiveStockRecommend;
use app\common\model\LiveStockSuggest;
use app\common\model\teacher\Teacher;
use app\common\model\Topic;
use think\Cache;
use think\Db;
use think\db\Query;
use think\Model;
use think\Validate;

/**
 * Class Live
 * @package app\api\controller
 *
 * @property integer uid
 */
class Live extends Base {

    protected $live;

    public function __construct()
    {
        parent::__construct();

        $this->live = new \app\api\model\live\Live();

        $this->uid = checkUserToken();
    }

    /**
     * @version v1.4
     * 直播间列表
     *
     * @return ApiResponse
     */
    public function room_list() {
        $form = $this->getAndCheckForm([
            ['page', 'integer',],
            ['rows', 'integer',],
            ['official', 'integer',],
        ]);

        //添加是否是官方筛选
        $form['official'] = isset($form['official'])?$form['official']:null;

        $list = LiveChannel::apiList($form['page']??1, $form['rows']??3, -1,
            $this->uid,$form['official']);
        return ApiResponse::success($list['data'],$list['total'],$list['per_page'],$list['last_page']);
    }

    /**
     * @version v1.4
     * 直播间详情
     *
     * @return ApiResponse
     */
    public function room_detail() {
        $form = $this->getAndCheckForm([
            ['id', 'require|integer',],
        ]);

        $form['token']=$form['token']??'';
        $data = LiveChannel::apiDetail($form['id'], $this->uid,$form['token']);
        if (is_null($data)) return ApiResponse::error(ApiResponse::ERR_RESOURCE_NON,'直播室Id无效');

        return ApiResponse::success($data);
    }

    /**
     * @version v1.4
     * 回看列表
     *
     * @return ApiResponse
     */
    public function playback_list() {
        $uid = checkUserToken();
        $form = $this->getAndCheckForm([
            ['page', 'integer',],
            ['rows', 'integer',],
            ['teacher_id', 'integer',],
            ['channel_id', 'integer',],
            ['date', 'date',],
            ['official', 'integer',],
        ]);
        $form['rows']=$form['rows']??10;
        //添加是否是官方筛选
        $form['official'] = isset($form['official'])?$form['official']:null;
        $list = LiveModel::playbackList($form['official'],$form['page']??1,$form['rows'],$form['date']??null,
            $form['teacher_id']??0,$form['channel_id']??0, $uid);

        return ApiResponse::success($list['data'],$list['total'],$form['rows'],$list['last_page']);
    }

    /**
     * @version v1.4
     * 回看筛选
     *
     * @return ApiResponse
     */
    public function playback_filters() {
        $form = $this->getAndCheckForm([
            ['year', 'integer','年份格式不争取']
        ]);
        $teachers = Teacher::names4Api();
        $channels = LiveChannel::listNames(-1,$form['year']??'');
        return ApiResponse::success([
            'teachers' => $teachers,
            'channels' => $channels,
        ]);
    }

    /**
     * @version v1.4
     * 回看详情
     *
     * @return ApiResponse
     */
    public function playback_detail() {
        $uid = checkUserToken();
        $form = $this->getAndCheckForm([
            ['id', 'require|integer',],
            ['relate_page', 'integer',],
        ]);
        $relatePage = $form['relate_page'] ?? 1;
        $token=$form['token']??'';

        $live = LiveModel::playbackDetail($form['id'], $uid,$token);
        if (is_null($live)) ApiResponse::error(ApiResponse::ERR_RESOURCE_NON,'节目不存在');

        if (1 == $relatePage) {
            $teacher = Teacher::get(function (Query $query) use ($live) {
                $query->alias('t')->join('teacher_degree d','t.degree_id=d.id','LEFT');
                $query->where('t.id',$live->teacher_id);
                $query->field('t.id,t.realname,t.avatar,t.num_followed,t.followed as set_followed,t.intro, d.name as degree');
            });
            $teacher->followed = false;
            if ($teacher && $this->uid>0) $teacher->followed = Teacher::checkFollow($live->teacher_id, $this->uid);

            // 老师文章总数统计
            $articleCount = Db::table('teacher_essay')->where('teacher_id', $live->teacher_id)->where('hide', 'false')->count();
            $teacher['article_total'] = $articleCount;

            // 老师课程视频总数统计
            $courseCount = Db::table('curriculum_video')->where('video_teacher', $live->teacher_id)->where('hide', 'false')->count();
            $teacher['course_total'] = $courseCount;

            // 老师问答总数统计
            $askCount = Db::table('ask')->where('ask_teacher', $live->teacher_id)->count();
            $teacher['ask_total'] = $askCount;

            $teacher['num_followed'] = countDataNum($teacher['num_followed'], $teacher['set_followed']);
            unset($teacher['set_followed']);
        }
        $live->teacher = $teacher ?? new \stdClass();

        $live->others = LiveModel::relatedPlayBackList($relatePage,5, null,0, $live->live_channel_id, 0, [$live->id]);

        return ApiResponse::success($live);
    }



    public function live_of_teacher() {
        $uid = checkUserToken();
        $form = $this->getAndCheckForm([
            ['teacher_id', 'require|integer',],
            ['page', 'integer',],
            ['limit', 'integer',],
        ]);
        $teacherId = intval($form['teacher_id']);
        $page = intval($form['page'] ?? 1);
        $rows = intval($form['rows'] ?? 10);

        $result = [];
        if (1 == $page) {
            $room = LiveChannel::get(['teacher_id' => $teacherId]);
            if (empty($room)) {
                $room = LiveChannel::get(['teacher_id' => 0]);
            }
            if ($room) {
                $live = LiveModel::get(function (Query $query) use ($room) {
                    $query->where('live_channel_id','=', $room->id);
                    $query->whereIn('status', [LiveModel::STATUS_START,LiveModel::STATUS_END,LiveModel::STATUS_RECORD,]);
                    $query->order('CASE status WHEN 1 THEN 1 WHEN 3 THEN 2 WHEN 2 THEN 3 END');
                    $query->order('id','desc');
                });

                if ($live) {
                    $roomData = ['id' => $room->id,'title'=>$live->title,'live_date'=>$live->live_date,'status'=>$live->status,'number_online'=>num2tring($live->number_online_peak)];
                } else {
                    $room->number_online = countDataNum($room->number_online, $room->online_num, true); // 当前在线人数
                    unset($room['online_num']);

                    $roomData = ['id' =>$room->id,'title'=>$room->name,'live_date'=>date('Y-m-d'),'number_online'=>$room->number_online];
                }

                $result[] = ['item_type' => 1, 'room' => $roomData, 'topic' => new \stdClass()];
                $rows -= 1;
            }
        }

        $re = Topic::apiList($teacherId, $rows, $page, $uid);
        foreach ($re['list'] as $item) {
            $result[] = ['item_type' => 2, 'room' => new \stdClass(), 'topic' => $item];
        }

        return ApiResponse::success($result);
    }



    /**
     * live_list
     * 直播节目数据接口
     * @api http://xxx/api/live
     *
     * @author zhengkai
     * @date 2017-08-24
     *
     * @return \think\response\Json
     */
    public function live_list()
    {
        // 登录检测
        // checkUserToken(true);

        return $this->live->get_live();
    }

    /**
     * live_detail
     * 直播详情数据接口
     * @api http://xxx/api/live/detail
     *      live_id 必填 直播节目id
     *
     * @author zhengkai
     * @date 2017-08-24
     *
     * @return \think\response\Json
     */
    public function live_detail()
    {
        // 登录检测
        $uid = checkUserToken(false);

        $form = input('post.');

        // 表单验证
        $validate = new Validate([
            ['live_id', 'require|^\\d+$', '直播id不能为空|参数类型不正确'],
        ]);

        if(!$validate->check($form)) return ApiResponse::error(ApiResponse::ERR_FORM_INVALID,$validate->getError());

        return $this->live->get_live_detail($uid,$form);
    }

    /**
     * live_program
     * 直播节目列表数据接口
     * @api http://xxx/api/live/program
     *      date 非必填 直播节目日期，格式：0000-00-00
     *
     * @author zhengkai
     * @date 2017-11-01
     * @version v1.1
     *
     * @return \think\response\Json
     */
    public function live_program()
    {
        $form = input('post.');
        if (array_key_exists('date', $form) || !empty($form['date'])) {
            $date = $form['date'];
        } else {
            $date = '';
        }

        return $this->live->query_live($date);
    }

    /**
     * live_make
     * 直播预约数据接口
     * @api http://xxx/api/live/make
     *      live_id 必填 直播节目id
     *
     * @author zhengkai
     * @date 2017-09-06
     *
     * @return \think\response\Json
     */
    public function live_make()
    {
        // 登录检测
        $uid = checkUserToken(true);

        return $this->live->insert_live_make($uid);
    }

    /**
     * live_like
     * 直播点赞接口
     * @api http://xxx/api/live/like
     *      live_id 必填 直播节目id
     *
     * @author zhengkai
     * @date 2017-08-24
     *
     * @return \think\response\Json
     */
    public function live_like()
    {
        // 登录检测
        // checkUserToken(true);

        return $this->live->update_live_like();
    }

    /**
     * 分享直播页面接口
     *
     * @return ApiResponse
     */
    public function live_share() {

        $sql = <<<SQL
SELECT l.id live_id,l.title live_title,l.start_time,l.end_time,l.live_date,l.cover,
  l.live_price > 0 is_fee, l.status live_status,t.realname teacher_name,
  (SELECT c.pullurlhls pull_url FROM live_channel c WHERE c.id=l.live_channel_id)
FROM live l JOIN teacher t ON l.teacher_id = t.id 
WHERE l.live_date=date(now())
SQL;
        $list = Db::query($sql);

        $current = null;
        foreach ($list as & $item) {
            $item['live_s_time'] = date('H:i', strtotime($item['start_time']));
            $item['live_e_time'] = date('H:i', strtotime($item['end_time']));
            if ($item['live_status'] == 1) {
                $current = $item;
            }
            unset($item['start_time'],$item['end_time']);
        }

        return ApiResponse::success([
            'list' => $list,
            'current' => $current,
        ]);
    }

    /**
     * 直播频道下的“操作建议”
     *
     * @return ApiResponse
     */
    public function operate_suggest() {
        $form = $this->getAndCheckForm([
            ['cid', 'require|integer',],
            ['rows', 'integer',],
            ['page', 'integer',],
        ]);

        $list = LiveStockSuggest::apiList($form['page']??1, $form['rows']??10, $form['cid']);

        return ApiResponse::success($list);
    }

    public function shaidan() {
        $form = $this->getAndCheckForm([
            ['live_id', 'require|integer',],
            ['rows', 'integer',],
            ['page', 'integer',],
        ]);

        $cid = \app\api\model\live\Live::getChannelId($form['live_id']);
        $list = LiveStockRecommend::apiList($form['rows']??10,$form['page']??1, $cid);

        return ApiResponse::success($list);
    }

    /**
     * web_live
     * web版直播首页数据接口
     * @api http://xxx/api/web/live
     *
     * @author zhengkai
     * @date 2017-11-14
     * @version 1.1
     *
     * @todo v1.4.1废弃
     *
     * @return \think\response\Json
     */
    public function web_live()
    {
        $uid = checkUserToken(false);

        return $this->live->getTodayLive($uid);
    }

    /**
     * web_live_player
     * web版直播节目播放请求数据接口
     * @api http://xxx/api/web/live/palyer
     *      POST
     *          live_id 必填 直播节目id
     *
     * @author zhengkai
     * @date 2017-11-14
     * @version 1.1
     *
     * @todo v1.4.1废弃
     *
     * @return \think\response\Json
     */
    public function web_live_player()
    {
        $uid = checkUserToken(false);

        $form = input('post.');

        // 表单验证
        $validate = new Validate([
            ['live_id', 'require|^\\d+$', '直播ID不能为空|参数类型不正确']
        ]);
        if(!$validate->check($form)) return json(array('code'=>1010, 'msg'=>$validate->getError(), 'data'=>null));

        return $this->live->getSingleLive($uid, $form['live_id']);
    }

    /**
     * pc_index
     * pc首页直播数据
     *
     * @author zhengkai
     * @date 2018-04-23
     *
     * @return array
     * @throws \think\exception\DbException
     */
    public static function pc_index()
    {
        $result = \app\api\model\live\Live::getNewPlayLive();
        $result['list'] = \app\api\model\live\Live::getChannelLive($result['live_channel_id'], $result['id']);

        return $result;
    }


    public function checkPassword(){
        $form = input('post.');
        // 表单验证
        $validate = new Validate([
            ['live_id', 'require|^\\d+$', '直播id不能为空|参数类型不正确'],
            ['password','length:0,4']
        ]);

        if(!$validate->check($form)) return ApiResponse::error(ApiResponse::ERR_FORM_INVALID,$validate->getError());
        $live=\app\api\model\live\Live::getOne($form['live_id'],'password,is_encrypt');
        if(!$live) return ApiResponse::error(ApiResponse::ERR_RESOURCE_NON,'节目不存在');
        if(!$live['is_encrypt'])   return ApiResponse::success(ApiResponse::SUCCESS,'');//视频未加密
        if(!isset($form['password']) || !$form['password']) return ApiResponse::error(ApiResponse::EMPTY_PWD,'请输入密码');
        if($form['password'] != $live['password']) ApiResponse::error(ApiResponse::ERR_PWD,'密码错误');

        $token=$this->liveToken($form['live_id'],$time=time());
        $data=[
            'token'=>$token,
            'live_id'=>$form['live_id'],
            'create_time'=>$time
        ];
        Db::name('live_token')->data($data)->insert();
        return ApiResponse::success(['token'=>$token]);
    }

    public function liveToken($live_id, $timestamp)
    {
        $token = md5(md5($live_id.$timestamp));
        return $token;
    }

}
